<?php
include_once("CSS.class.php");
include_once("JS.class.php");
include_once("EventManager.class.php");

class Element
{
	var $form;
	var $conn = null;
	var $ID;
	var $name;
	var $type;
	var $label;
	var $size;
	var $help;
	var $js;
	var $css;
	var $required = false;
	var $error;
	var $__error;
	var $default;
	var $events;
	var $template = array(
						'col'   => "{label}\n<td{params} valign=\"top\">{input}{help}\n\t\t</td>\n",
						'error' => "<span style=\"color: red; font-weight: bold\">{error}</span>",
						'label' => "<td align=\"right\" valign=\"top\" class=\"label\"><label for=\"{id}\">{label}</label></td>",
						'help'  => "<br /><small>{help}</small>"
					);
	var $colspan = 0;
	var $isPostBack = false;
	var $invalid = false;
	var $VALUE;

	function Element($id)
	{
		$this->ID = $id;
		$this->css = new CSS;
		$this->js  = new JS($this);
		$this->events = new EventManager;

		if ($_POST['postBack'] == 'sended')
		{
			$this->isPostBack = true;
			$this->default = $this->__getPostBackValue();
		}
	}

	function setForm(&$form)
	{
		$this->form = &$form;
	}

	function __getPostBackValue()
	{
		return $_POST[$this->getName()];
	}

	function getParams()
	{
		return
		$this->css->getCSS() .
		$this->events->getEvents();
	}

	function __getColspan()
	{
		if ($this->colspan != 0)
		{
			return " colspan=\"".$this->colspan."\"";
		}
		return "";
	}

	function getHTML()
	{
		if ($this->isPostBack && !$this->isValid())
		{
			$this->label      = str_replace('{error}', $this->__getError(), $this->template['error']);
			$this->__setValue($this->default);
		}
		$help = "";
		if (!empty($this->help))
		{
			$help = str_replace("{help}", $this->help, $this->template['help']);
		}

		return str_replace(array('{params}', '{label}', '{input}', '{id}', '{help}'), array($this->__getColspan(), $this->__getLabel(), $this->__getHTML(), $this->ID, $help), $this->template['col']);
	}

	function __getHTML()
	{
		die("no implementado!");
	}

	function __getLabel()
	{
		if (!empty($this->label))
		{
			return str_replace(array('{label}', '{id}'), array($this->label, $this->ID), $this->template['label']);
		}
		return "";
	}

	function __getError()
	{
		return empty($this->error) ? $this->label : $this->error;
	}

	function getName()
	{
		return empty($this->name) ? $this->ID : $this->name;
	}

	function isValid()
	{
		if ($this->isPostBack && (($this->required && empty($this->default)) || $this->invalid) || !$this->isPostBack)
		{
			if ($this->isPostBack)
			{
				$this->form->addError($this->__getError());
			}
			return false;
		}

		return true;
	}

	function setDefault($default)
	{
		if (!$this->isPostBack)
		{
			$this->default = $default;
		}
	}

	function getValue()
	{
		return $this->VALUE;
	}

	function __setValue($value)
	{
		$this->VALUE = $value;
	}

}

?>